package com.qf.service;

import com.qf.entity.Goods;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SearchServiceImpl {

    @Autowired
    private RestHighLevelClient client;

    @Value("${es.indexName}")
    private String indexName;

    @Value("${es.typeName}")
    private String typeName;

    /**
     * @param keyword 搜索关键字
     * @param orderBy 排序字段 1:默认，2:价格，3：商品id
     * @return
     * @throws Exception
     */
    public List<Goods> searchGoodsList(String keyword, Integer orderBy) throws Exception {
        List<Goods> goodsList = new ArrayList<>();

        // 1.创建一个请求对象
        SearchRequest request = new SearchRequest(indexName);

        // 3.设置高亮字段的属性
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        HighlightBuilder builder = new HighlightBuilder();
        builder.field("gname"); // 高亮字段
        builder.preTags("<font color ='red'>");
        builder.postTags("</font>");
        builder.fragmentSize(20);

        searchSourceBuilder.highlighter(builder);

        // 2.设置搜索的关键字
        if (StringUtils.isEmpty(keyword)) {
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        } else {
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, "gname", "gdesc"));
        }

        // 设置排序规则
        if (orderBy == 2) {
            searchSourceBuilder.sort("gprice", SortOrder.DESC);
        } else if (orderBy == 3) {
            searchSourceBuilder.sort("id", SortOrder.DESC);
        }

        request.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (int i = 0; i < hits.length; i++) {
            Map<String, Object> sourceAsMap = hits[i].getSourceAsMap();

            Goods goods = new Goods();
            BeanUtils.populate(goods, sourceAsMap);

            Map<String, HighlightField> highlightFields = hits[i].getHighlightFields();
            if (!highlightFields.isEmpty()) {
                HighlightField gnameHigh = highlightFields.get("gname");
                String s = gnameHigh.fragments()[0].toString();
                goods.setGname(s);
            }
            System.out.println(goods);
            goodsList.add(goods);
        }
        return goodsList;
    }
}
